package com.crcode.crm.service.data.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crcode.crm.bean.data.EnterpriseBean;
import com.crcode.crm.bean.data.ProjectBean;
import com.crcode.crm.bean.log.DataLogBean;
import com.crcode.crm.bean.user.UserBean;
import com.crcode.crm.dao.accessory.AccessoryDao;
import com.crcode.crm.dao.data.EnterpriseDao;
import com.crcode.crm.dao.data.ProjectDao;
import com.crcode.crm.dao.log.DataLogDao;
import com.crcode.crm.dao.progress.ProgressDao;
import com.crcode.crm.service.data.EnterpriseService;
import com.crcode.crm.utils.DateUtil;
import com.crcode.crm.utils.MyFileUtil;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.ResultPageUtil;
import com.crcode.crm.utils.ResultUtil;

@Service(value="enterpriseService")
@Transactional
public class EnterpriseServiceImpl implements EnterpriseService {

    @Autowired
    EnterpriseDao enterpriseDao;

    @Autowired
    ProgressDao progressDao;

    @Autowired
    AccessoryDao accessoryDao;

    @Autowired
    ProjectDao projectDao;

    @Autowired
    DataLogDao logDao;

    @Override
    public List<EnterpriseBean> findByEntName(String name) {
        return enterpriseDao.findByEntName(name);
    }

    @Override
    public EnterpriseBean findByUuid(String uuid) {
        return enterpriseDao.findByUuid(uuid);
    }

    @Override
    public boolean deleteByIdIn(List<Integer> ids, List<String> uuidList, UserBean user) {
        try {
            enterpriseDao.deleteByIdIn(ids); // 根据id删除企业
            // 删除企业相关的附件，进度，项目
            for(String uuid : uuidList) {
                //删除方案
                accessoryDao.deleteByDataUuid(uuid);
                //删除进度
                progressDao.deleteByDataUuid(uuid);
                //删除文件
                MyFileUtil.deleteFile("project/" + uuid + "/plan");
                MyFileUtil.deleteFile("project/" + uuid + "/progress");
            }
            //删除项目
            // 先保存日志
            String thisTime = DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
            List<ProjectBean> projects = projectDao.findByEntUuidIn(uuidList);
            List<DataLogBean> logs = new ArrayList<>();
            for(ProjectBean project : projects) {
                DataLogBean log = new DataLogBean();
                log.setUserUuid(user.getUuid());
                log.setUserName(user.getUserRealName());
                log.setOperateTime(thisTime);
                log.setDataTuid(project.getUuid());
                log.setDataTitle(project.getProName());
                log.setOriginalContent(JSON.toJSONString(project));
                log.setOperateRemarks("项目资源删除");
                log.setLogType(1);
                log.setDetailedType(3);
                logs.add(log);
            }
            logDao.saveAll(logs);
            projectDao.deleteByEntUuidIn(uuidList);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public EnterpriseBean getById(Integer integer) {
        return enterpriseDao.findById(integer).orElse(null);
    }

    @Override
    public EnterpriseBean saveResultBean(EnterpriseBean enterpriseBean) {
        return enterpriseDao.save(enterpriseBean);
    }

    @Override
    public boolean saveResultBoolean(EnterpriseBean enterpriseBean) {
        try {
            enterpriseDao.save(enterpriseBean);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public EnterpriseBean updateResultBean(EnterpriseBean enterpriseBean) {
        return enterpriseDao.save(enterpriseBean);
    }

    @Override
    public boolean updateResultBoolean(EnterpriseBean enterpriseBean) {
        try {
            enterpriseDao.save(enterpriseBean);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean delete(Integer integer) {
        try {
            enterpriseDao.deleteById(integer);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public List<EnterpriseBean> getAll() {
        return enterpriseDao.findAll();
    }

    @Override
    public ResultPageUtil findByEntNameContaining(String search, PageVo vo) {
        Integer pageIndex = vo.getPageIndex() - 1;
        Pageable pageable = null;
        if(StringUtils.isNotBlank(vo.getOrderBy())){
            if(vo.getOrderDesc() == 0){
                pageable = PageRequest.of(pageIndex, vo.getPageSize(), Sort.Direction.ASC, vo.getOrderBy());
            }else if(vo.getOrderDesc() == 1){
                pageable = PageRequest.of(pageIndex, vo.getPageSize(), Sort.Direction.DESC, vo.getOrderBy());
            }
        }else{
            pageable = PageRequest.of(pageIndex, vo.getPageSize());
        }
        Page<EnterpriseBean> page = enterpriseDao.findByEntNameContaining(search, pageable);
        ResultPageUtil resultPageUtil = new ResultPageUtil();
        resultPageUtil.setCurrentPage(vo.getPageIndex());
        resultPageUtil.setPageSize(vo.getPageSize());
        resultPageUtil.setTotalPages(page.getTotalPages());
        resultPageUtil.setRows(page.getContent());
        resultPageUtil.setTotal(page.getTotalElements());
        return resultPageUtil;
    }
    /**
     * 根据UUIDS设置可见权限
     * @author lxw
     * @date 2019年4月9日
     * @param uuids 资源UUIDS
	 * @param suuid 查看权限用户UUIDS
	 * @param sname查看权限用户名称集
	 * @param euuid编辑 权限用户UUIDS
	 * @param ename编辑权限用户名称集
	 * @param user 当前操作用户
     * @return
     */
    @Override
    public boolean empowerByIds(String uuids,String suuid,String sname,String euuid,String ename,UserBean user){
    	String nowTime=DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
		List<String> ul = Arrays.asList(uuids.split(","));
    	List<EnterpriseBean> le = this.enterpriseDao.findByUuidIn(ul);
    	List<EnterpriseBean> nel = new ArrayList<>();
    	List<DataLogBean> logs = new ArrayList<>();
    	for (EnterpriseBean ent : le) {
    		EnterpriseBean en=ent;
    		ent.setSearchPowerUserUuids(suuid);
    		ent.setSearchPowerUserName(sname);
    		ent.setEditPowerUserUuids(euuid);
    		ent.setEditPowerUserName(ename);
    		nel.add(ent);
			//保存日志
			DataLogBean log = new DataLogBean();
			log.setUserUuid(user.getUuid());
			log.setUserName(user.getUserRealName());
			log.setOperateTime(nowTime);
			log.setDataTuid(ent.getUuid());
			log.setDataTitle(ent.getEntName());
			log.setLatestContent(JSONObject.toJSONString(ent));
			log.setLogType(0);
			log.setOriginalContent(JSONObject.toJSONString(en));
			log.setOperateRemarks("管理员分配该企业资源查看，编辑权限");
			log.setDetailedType(0);
			logs.add(log);
        }
    	boolean is = false;
    	try {
    		this.enterpriseDao.saveAll(nel);
    		logDao.saveAll(logs);
    		is =true;
    		progressDao.updatePowerInfoByDataUuids(suuid, sname, euuid, ename, ul);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return is;
    }

    /**
     * 根据ids查询多个企业
     * @param ids ids
     * @return
     */
    @Override
    public List<EnterpriseBean> findByIdIn(List<Integer> ids) {
        return enterpriseDao.findByIdIn(ids);
    }

    /**
     * 根据名称等于，uuid不等于查询
     * @author lxw
     * @date 2019年4月12日
     * @param name
     * @param uuid
     * @return
     */
	@Override
	public List<EnterpriseBean> findByEntNameAndUuidNot(String name, String uuid) {
		return this.enterpriseDao.findByEntNameAndUuidNot(name, uuid);
	}

    /**
     * 根据用户/创建时间统计企业数量,按天统计
     * @return List<Map<String, Object>>
     */
    @Override
    public List<Map<String, Object>> aggsEntByUserCreateTime(String uuid) {
        return this.enterpriseDao.aggsEntByUserCreateTime(uuid);
    }
    /**
	 * 设置项目的启动或者终止
	 * @author lxw
	 * @date 2019年4月19日
	 * @param isEnd 0、正常，1、终止
	 * @param uuids
	 * @return
	 */
	public ResultUtil setEntStartOrEnd(UserBean user,Integer isEnd, String uuids){
		List<String> uuidl = Arrays.asList(uuids.split(",")); 
		ResultUtil r = new ResultUtil();
		this.progressDao.updateProStatsByDataUuids(isEnd, uuidl);
		long x = this.enterpriseDao.updateEntStatsByUuids(isEnd, uuidl);
		if(x>0){
			List<DataLogBean> logs = new ArrayList<>();
			String nowTime=DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
			List<EnterpriseBean> pl = this.enterpriseDao.findByUuidIn(uuidl);
			for (EnterpriseBean pro : pl) {
				//保存日志
				DataLogBean l = new DataLogBean();
				l.setUserUuid(user.getUuid());
				l.setUserName(user.getUserRealName());
				l.setOperateTime(nowTime);
				l.setDataTuid(pro.getUuid());
				l.setDataTitle(pro.getEntName());
				l.setLatestContent(JSONObject.toJSONString(pro));
				l.setLogType(0);
			
				pro.setEntStats(isEnd);
				l.setOriginalContent(JSONObject.toJSONString(pro));
				l.setOperateRemarks(user.getUserRealName()+(isEnd==0?"-恢复了企业":"-终止了企业"));
				l.setDetailedType(0);
				logs.add(l);
			}
			this.logDao.saveAll(logs);
		}
		r.setInfo(x>0?"操作成功":"操作失败");
		r.setStatus(x>0);
		return r;
	}
	

	/**
	 * 重置负责人
	 * @author lxw
	 * @date 2019年4月26日
	 * @param user 操作者
	 * @param uuids 资源UUIDS
	 * @param userUuid 用户序号
	 * @param userName 用户名称
	 * @return
	 */
	@Override
	public ResultUtil resetLiableUserByUuids(UserBean user, String uuids, String userUuid, String userName) {
		ResultUtil r = new ResultUtil();
		List<String> uuidl = Arrays.asList(uuids.split(",")); 
		List<EnterpriseBean> opl = this.enterpriseDao.findByUuidIn(uuidl);
		long x  = this.enterpriseDao.updateProLiableUserByUuids(userUuid, userName, uuidl);
		if(x>0){
			List<DataLogBean> logs = new ArrayList<>();
			String nowTime=DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
			for (EnterpriseBean pro : opl) {
				//保存日志
				DataLogBean l = new DataLogBean();
				l.setUserUuid(user.getUuid());
				l.setUserName(user.getUserRealName());
				l.setOperateTime(nowTime);
				l.setDataTuid(pro.getUuid());
				l.setDataTitle(pro.getEntName());
				l.setLatestContent(JSONObject.toJSONString(pro));
				l.setLogType(0);
				pro.setLiableUserUuid(userUuid);
				pro.setLiableUserName(userName);
				l.setOriginalContent(JSONObject.toJSONString(pro));
				l.setOperateRemarks(user.getUserRealName()+("：将企业负责人更改为["+userName+"]"));
				l.setDetailedType(3);
				logs.add(l);
			}
			this.logDao.saveAll(logs);
		}
		r.setInfo(x>0?"操作成功":"操作失败");
		r.setStatus(x>0);
		return r;
	}
}
